package com.achievo.know.job;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.achievo.know.application.FileApplication;
import com.achievo.know.component.impl.FileManagerConfig;
import com.achievo.know.domain.FileAttachmentRepository;

public class ConvertPDFFileDailyJob {
	
	@Autowired
	private FileManagerConfig config;
	@Autowired
	private FileAttachmentRepository attsReps;
	@Autowired
	public FileApplication fileApplication;
	
	
	
	ExecutorService service=Executors.newCachedThreadPool();

	public void setFileApplication(FileApplication fileApplication) {
		this.fileApplication = fileApplication;
	}

	public FileManagerConfig getConfig() {
		return config;
	}

	public void setConfig(FileManagerConfig config) {
		this.config = config;
	}

	public FileAttachmentRepository getAttsReps() {
		return attsReps;
	}

	public void setAttsReps(FileAttachmentRepository attsReps) {
		this.attsReps = attsReps;
	}

	public void work() {
		try {
			System.out.println("任务调度:转换PDF文件为SWF文件");
			//先杀掉存在的pdf2swf进程
			Runtime.getRuntime().exec("TASKKILL /F /T /IM pdf2swf.exe ");
			//只处理当月的
			SimpleDateFormat format=new SimpleDateFormat("yyyyMM/");
			String monthPath=format.format(new Date());
			File persist=new File(config.getPersistFileStoreDirectory(),monthPath);
			if(persist.exists()){
				File[] pdfs=persist.listFiles();
				for(File z:pdfs){
					String ext=FilenameUtils.getExtension(z.getName());
					String guid=FilenameUtils.getBaseName(z.getName());
					if(ext!=null && ext.equalsIgnoreCase("pdf")){
						boolean isOk =false;
						java.io.File oFile=new java.io.File(config.getSwfFileStoreDirectory()+java.io.File.separator+guid+ java.io.File.separator+"1.swf");
						if(oFile.exists()){
							isOk= true;
						}
						if(!isOk){
							ConvertFileThread task=new ConvertFileThread(getConfig(),monthPath,guid,ext,fileApplication);
							Future<Boolean> result=service.submit(task);
							System.out.println("submitted task "+guid);
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
